#include "videoplayer.h"

//空构造函数，用于创建对象
VideoPlayer::VideoPlayer(QWidget *parent)
{
    Q_UNUSED(parent)
    setStyleSheet("background-color: white;");//设置窗体背景颜色为白色
    mvUrl_manager = new QNetworkAccessManager(this);//mv信息

    //绑定歌曲搜索信息、歌单图片网络请求信号
    connect(mvUrl_manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
}

VideoPlayer::~VideoPlayer()
{
    delete mv_player;
    delete mv_playlist;
    delete videoWidget;
    delete mv_slider;
    delete mvUrl_manager;
}

//mv信息请求槽
void VideoPlayer::replyFinished(QNetworkReply*reply)
{
    //判断网页是否响应成功
    //    QNetworkRequest::HttpStatusCodeAttribute网址返回的状态码
    if(200==reply->attribute(QNetworkRequest::HttpStatusCodeAttribute))
    {
        parseJson_mv(reply->readAll());//解析mvjson数据

//        qDebug()<<"mvUrl="<<mvUrl;
        mv_playlist->addMedia(QUrl(mvUrl));
        // 设置播放列表
        mv_player->setPlaylist(mv_playlist);

        // 创建视频输出窗口
        videoWidget = new QVideoWidget(this);
        videoWidget->setFullScreen(false);
        mv_player->setVideoOutput(videoWidget);

        // 创建进度条
        mv_slider = new QSlider(Qt::Horizontal, this);
        mv_slider->setRange(0, 0);
        //设置进度条样式
        mv_slider->setStyleSheet
                (
                    "QSlider:horizontal {"
                               "   height: 6px;"
                               "   margin: 0px 20px;"
                               "}"
                               "QSlider::groove:horizontal {"
                               "   background: #d3d3d3; /* 浅灰色 */"
                               "   height: 2px;"
                               "   border-radius: 1px;"
                               "}"
                               "QSlider::sub-page:horizontal {"
                               "   background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1, stop: 0 #ff6b6b, stop: 1 #c94c4c);"
                               "   border: 1px #b22222;"
                               "   height: 2px;"
                               "   border-radius: 1px;"
                               "}"
                               "QSlider::add-page:horizontal {"
                               "   background: #d3d3d3; /* 浅灰色 */"
                               "   border: 1px #b22222;"
                               "   height: 2px;"
                               "   border-radius: 1px;"
                               "}"
                               "QSlider::handle:horizontal {"
                               "   background: #ff3d00;"
                               "   width: 12px;"
                               "   margin: -3px 0;"
                               "   border-radius: 6px;"
                               "}"
               );
        connect(mv_player, &QMediaPlayer::durationChanged, mv_slider, &QSlider::setMaximum);
        connect(mv_player, &QMediaPlayer::positionChanged, mv_slider, &QSlider::setValue);
        connect(mv_slider, &QSlider::sliderMoved, mv_player, &QMediaPlayer::setPosition);

        // 设置布局
        layout = new QVBoxLayout(this);
        layout->addWidget(videoWidget);
        layout->addWidget(mv_slider);
        setLayout(layout);

        // 播放视频
        mv_playlist->setCurrentIndex(0);
        mv_player->play();

        // 更新进度条
        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &VideoPlayer::updateSlider);
        timer->start(1000);//每隔1秒更新

        // 安装事件过滤器
        videoWidget->installEventFilter(this);
    }
    else
    {
        QMessageBox::warning(this,"网页访问失败","请求超时!");
    }
    reply->deleteLater(); // 清理回复
}
//播放MV
void VideoPlayer::Play_mv(int mvid)
{
    // 解析加载mv信息
    mvUrl_manager->get(QNetworkRequest(QUrl(QString("https://music.163.com/api/mv/detail?id=%1").arg(mvid))));

    // 创建媒体播放器和播放列表
    mv_player = new QMediaPlayer(this);
    mv_playlist = new QMediaPlaylist(mv_player);

}

//关闭MV
void VideoPlayer::close()
{
    mv_player->stop();
    videoWidget->close();
    delete layout;
//    QWidget::close();
}

//暂停MV
void VideoPlayer::pasue()
{
    mv_player->pause();
}

//继续播放MV
void VideoPlayer::play()
{
    mv_player->play();
}

//解析MV视频信息
void VideoPlayer::parseJson_mv(QByteArray byteArray)
{

    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    if(doc.isObject())//问文档内部是否是一个对象？
    {
        QJsonObject obj = doc.object();//返回文档内的对象
        if(obj.contains("data") == false)//问文档对象是否包含data关键字
        {
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        QJsonValue var = obj.value("data");//获得关键字data对应的结果
        if(var.isObject() == false)
        {
            qDebug()<<"songs的值不是一个对象"<<endl;
            return;
        }
        QJsonObject dataObj = var.toObject();//把data的值转为一个对象
        if(dataObj.contains("brs"))
        {
            var=dataObj.value("brs");
            QJsonObject brsObj=var.toObject();
            if(brsObj.contains("720"))
            {
                var=brsObj.value("720");
                mvUrl=var.toString();//获取对应mvid的mv地址信息
//                qDebug()<<"jiexi"<<mvUrl;
            }
        }
    }
}

//MV全屏缩小关闭快捷键
void VideoPlayer::keyPressEvent(QKeyEvent *event)
{
    //Esc-缩小
    if (event->key() == Qt::Key_Escape)
    {
        videoWidget->setFullScreen(false); // 退出全屏
        videoWidget->setMinimumSize(1075,600);
    }
    //f-放大
    if(event->key() == Qt::Key_F)
    {
        videoWidget->setFullScreen(true);
    }
    //c-关闭
    if(event->key() == Qt::Key_C)
    {
        //关闭视频窗口
        videoWidget->close();
        mv_player->stop();
        QWidget::close();
    }
}

//事件过滤器
bool VideoPlayer::eventFilter(QObject *obj, QEvent *event)
{
    // 检查事件的对象是否是 videoWidget，且事件类型是否是键盘按下事件
    if (obj == videoWidget && event->type() == QEvent::KeyPress)
    {
        // 将事件对象转换为 QKeyEvent，以便于处理键盘事件
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        keyPressEvent(keyEvent);    // 调用 keyPressEvent 方法，处理键盘按下事件
        return true; // 事件已处理
    }
    return QWidget::eventFilter(obj, event); // 继续处理其他事件
}
